package com.gxa.saas.portal.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.saas.core.exception.BusinessException;
import com.gxa.saas.core.exception.ExceptionCode;
import com.gxa.saas.core.utils.RestUtils;
import com.gxa.saas.portal.thread.UserThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private UserThreadLocal userThreadLocal;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从前端的请求头中获取token
        String token = request.getHeader("token");

        //判断token，如果为null，直接拦截
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }
        //通过发起SSO服务器的RPC
//        String url = "http://localhost:8090/user/checkWithToken";
        String url = "http://43.142.113.212:8090/user/checkWithToken";
        Map<String ,String> headers = new HashMap<>();
        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("token",token);
        Map map = RestUtils.postWithParams(url,headers,params);
        if (!map.get("code").equals("200")) {
            //FIXME SSO校验token不通过，也给前端信息
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        Object data = map.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(data);
        userThreadLocal.set(jsonString);
        return true;
    }
}
